<template>
  <div class="department-container">
    <div class="app-container">
      <page-tools title="总结路数据20条">
        <!-- v-if="$store.state.user.setUserInfo.roles.points.includes('import_excel')" -->
        <el-button
          v-allow="'import_excel'"
          type="warning"
          size="small"
          @click="$router.push('/import')"
        >excel导入</el-button>

        <!-- v-if="$store.state.user.setUserInfo.roles.points.includes('export_excel')" -->
        <el-button
          v-allow="'export_excel'"
          type="danger"
          size="small"
          @click="hExport"
        >excel导出</el-button>
        <el-button type="primary" size="small" @click="add">新增员工</el-button>
      </page-tools>

      <!-- 主体内容
      sortable 排序
      :default-sort 默认排序方式
      -->
      <el-card style="margin-top: 10px">
        <el-table border :data="list" :default-sort="{ prop: 'timeOfEntry' }">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template slot-scope="{row:{staffPhoto:res}}">
              <!-- <img :src="res"> -->
              <ImageHolder :src="res" />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" sortable label="入职时间" />
          <!-- <el-table-column prop='username' label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hassignRole(row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="Del(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!-- 分页功能 -->
          <el-pagination
            :current-page="params.page"
            :page-sizes="[2, 4, 6, 10]"
            :page-size="params.size"
            layout="total, sizes, prev, pager, next "
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 弹窗 -->
      <el-dialog
        title="添加"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <empDialog v-if="showDialog" @closeLoad="closeLoad" @cancel="cancel" />
      </el-dialog>

      <!-- 添加员工 -->
      <el-dialog
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialogRole"
      >
        <!-- v-if="showDialogRole"  销毁组件 避免子组件created 只执行一次 无法更新数据-->
        <assignRole v-if="showDialogRole" :id="Id" @success="successRole" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { list_type } from '@/const_zjf/constest.js'
import { getEmployeeList, delEmployee } from '@/api/employees'
import empDialog from './empDialog.vue'
import assignRole from './assignRole.vue'
export default {
  components: {
    empDialog,
    assignRole
  },
  data() {
    return {
      list: [], // 存放数据
      total: 0, // 记录总条数
      Id: '',
      params: {
        pag: 1,
        size: 6
      },
      showDialog: false,
      showDialogRole: false // 权限弹窗
    }
  },

  created() {
    this.emList()
  },
  methods: {
    // 权限弹窗
    hassignRole(id) {
      console.log(id, '分配角色id')
      this.showDialogRole = true
      // 分配角色 把id 传过去
      this.Id = id
    },
    // 保存 角色 成功
    successRole() {
      this.showDialogRole = false
      this.$message.success('保存角色成功!')
    },
    async emList() {
      const res = await getEmployeeList(this.params)
      console.log(res.data)
      this.list = res.data.rows // 存数据
      this.total = res.data.total
    },
    formatEmployment(type) {
      return list_type[type]
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.params.size = val
      this.params.page = 1 // 切换条数  切换到第一页
      this.emList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.params.page = val
      this.emList()
    },
    // 删除
    Del(id) {
      this.$confirm('确认删除吗?', '系统提示')
        .then(async() => {
          // 1. 传入id  删除
          await delEmployee(id)
          // 2. 提示用户
          this.$message.success('删除成功!')
          // 3. 删除最后一条数据 页码减1
          if (this.list.length === 1 && this.params.page > 1) {
            this.params.page--
          }
          // 4.重新渲染页面
          this.emList()
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 新增
    add() {
      this.showDialog = true
    },
    // 新增成功 关闭弹窗
    closeLoad() {
      //  1.关闭弹窗
      this.showDialog = false
      // 2. 新增数据 添加到页码最后
      this.total++
      this.params.page = Math.ceil(this.total / this.params.size)
      //  3.更新列表数据
      this.emList()
    },
    // 点击取消
    cancel() {
      this.showDialog = false
    },

    formatDate(rows) {
      const objmap = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const enHeader = Object.keys(rows[0]) // 表头
      const header = enHeader.map(en => objmap[en]) // 英文表头转中文

      // 内容部分
      const data = rows.map(obj => {
        obj.formOfEmployment = list_type[obj.formOfEmployment]
        return Object.values(obj)
      })
      return { header, data }
    },

    // 导出文件
    async hExport() {
      // 1.发请求拿数据
      const res = await getEmployeeList(this.params)
      console.log(res.data)
      // 2.对数据进行格式转换
      const { header, data } = this.formatDate(res.data.rows)
      // 3. 导出
      console.log('员工信息', header, data)
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    }
  }
}
</script>
<style scoped lang="scss" >
  /* 父组件下 +scoped /deep/ */
::v-deep img{
     width: 80px;
     height: 80px;
     border-radius: 50%;
  }
</style>
